from PIL import Image

__file__ = 'imageToChar.py'
__author__ = 'Jerry Liu'
__date__ = '2016-04-19'

"""
    问题：图片转为字符画
    原理：我们首先将图片变成黑白的，那么每个像素的取值范围为：0-255.
        然后我们将0-255映射到0-14的范围上，然后用如下字符代替：
        color = ‘MNHQ$OC?7>!:-;.’
        也就是像素为0的点用“M”表示，像素为14的点用“.”表示。
"""
color = 'MNHQ$OC?7>!:-;.'

def gethtml(func):
    html_head = '''
            <html>
              <head>
                <style type="text/css">
                  body {font-size:5px;}
                </style>
              </head>
            <body> '''

    html_tail = '</body></html>'

    def wrapper(img):
        pic_str = func(img)
        pic_str = ''.join(l + ' <br/>' for l in pic_str.splitlines())
        return html_head + pic_str + html_tail

    return wrapper

@gethtml
def make_char_img(img):
    pix = img.load()
    pic_str = ''
    width, height = img.size
    for h in range(height):
        for w in range(width):
            c = (pix[w, h]) * 14 / 255
            pic_str += color[int(c)]
        pic_str += '\n'
    return pic_str

def preprocess(img_name):
    img = Image.open(img_name)
    w, h = img.size
    m = max(img.size)
    delta = m / 300.0
    w, h = int(w / delta), int(h / delta)
    img = img.resize((100, 100))
    img = img.convert('L')
    # img.save('d://t-c.jpg')
    return img

def savehtml(path, pic_str):
    outfile = open(path, 'w')
    outfile.write(pic_str)
    outfile.close()

def main():
    img = preprocess('d:///t-c.jpg')
    pic_str = make_char_img(img)
    savehtml('d://char.html', pic_str)

if __name__ == '__main__':
    main()
